<template>
  <el-container style="background-color: #fff">
    <el-aside style="padding: 20px; box-sizing: border-box">
      <avue-tree
        :option="treeOption"
        :data="treeData"
        @node-click="handleTreeClick"
        style="height: calc(100% - 50px)"
      ></avue-tree>
    </el-aside>
    <el-main>
      <basic-crud
        :option="option"
        ref="basicCrudRef"
        :apiAddParams="{ userType: 3 }"
        selectType="radio"
      >
        <template #menu-left>
          <el-button
            icon="el-icon-plus"
            :loading="relationRoleOpenBtnLoading"
            @click="handleOpenRelationRoleDialog"
            >关联角色</el-button
          >
          <basic-import-btn
            @afterUploadSuccess="afterUploadSuccess"
            templateUrl="/permission/userController/downloadImportTemp"
            uploadUrl="/permission/userController/importData"
          ></basic-import-btn>
        </template>
        <template #status="{ row }">
          <el-tag v-if="row.resignFlag === 'true'" type="info">离职</el-tag>
          <el-tag
            v-else
            :type="row.status === 'Disabled' ? 'danger' : 'primary'"
            >{{ row.statusShow }}
          </el-tag>
        </template>
        <template #menu="{ row }">
          <el-button
            type="primary"
            link
            icon="EditPen"
            @click="handleOpenEditPas(row)"
            >修改密码</el-button
          >
          <el-dropdown style="vertical-align: middle; margin-left: 12px">
            <el-button type="primary" link icon="More">更多</el-button>
            <template #dropdown>
              <el-dropdown-menu size="small">
                <el-dropdown-item
                  @click="handleMoreItemClick('unlock', row)"
                  icon="Unlock"
                  >解锁</el-dropdown-item
                >
                <el-dropdown-item
                  @click="handleMoreItemClick('disabled', row)"
                  v-if="row.status === 'Enabled'"
                  icon="CircleCloseFilled"
                  >停用</el-dropdown-item
                >
                <el-dropdown-item
                  v-else
                  @click="handleMoreItemClick('enable', row)"
                  icon="CircleCheckFilled"
                  >启用</el-dropdown-item
                >
                <el-dropdown-item
                  @click="handleMoreItemClick('resign', row)"
                  icon="TopRight"
                  v-if="'true' !== row.resignFlag"
                  >离职</el-dropdown-item
                >
                <el-dropdown-item
                  v-else
                  @click="handleMoreItemClick('resign', row)"
                  icon="BottomLeft"
                  >返聘</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </basic-crud>
    </el-main>
  </el-container>
  <basic-dialog
    v-model="editPasVisible"
    title="修改密码"
    destroy-on-close
    @submit="handleSubmitEditPas"
    :before-close="handleBeforeClose"
    :submitBtnLoading="editPasSubmitLoading"
  >
    <el-form
      :model="editPasFormData"
      :rules="editPasRules"
      label-width="100"
      ref="editPasFormRef"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item prop="password" label="新密码">
            <el-input
              v-model="editPasFormData.password"
              type="password"
              autocomplete="off"
              show-password
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="confirmPassword" label="确认密码">
            <el-input
              v-model="editPasFormData.confirmPassword"
              type="password"
              show-password
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </basic-dialog>
  <basic-dialog-table
    v-model="relationRoleVisible"
    selectType="multiple"
    title="关联角色"
    :apiSource="apiSource"
    :option="relationRoleOption"
    :defaultSelectList="relationRoleDefaultSelectList"
    :submitBtnLoading="relationRoleSubmitLoading"
    @submit="handleRelationRoleSubmit"
  >
    <template #footer-left
      >原已选角色：{{
        relationRoleDefaultSelectList.map((item) => item.name).join('、')
      }}</template
    ></basic-dialog-table
  >
</template>

<script setup>
import { apiEditPwd } from '@/apis/permission/userManage.js'
import { ElMessage } from 'element-plus'
import { apiDialogGetList } from '@/apis/orgManage/dutyManage.js'
import { reactive } from 'vue'
import {
  apiUnlock,
  apiDisable,
  apiEnable,
  apiRehiring,
  apiResign,
  apiRelationRole,
  apiGetDepTree,
  apiGetLinkRoles,
} from '../../../apis/permission/userManage'
import { apiGetList as apiGetRoleList } from '@/apis/permission/roleManage.js'
const depList = ref([])
const basicCrudRef = ref()
const treeData = ref([])
const treeOption = ref({
  defaultExpandAll: true,
  addBtn: false,
  editBtn: false,
  delBtn: false,
  props: {
    label: 'name',
    value: 'id',
    children: 'children',
  },
})
const option = ref({
  menuWidth: 320,
  searchSpan: 8,
  selection: true,
  column: [
    {
      label: '用户名',
      prop: 'code',
      sortable: true,
      search: true,
      fixed: true,
      width: 180,
      editDisabled: true,
      rules: [
        {
          required: true,
          message: '用户名不能为空',
          trigger: 'blur',
        },
        {
          pattern: /^[A-Za-z0-9]+$/,
          message: '用户名只能包含英文与数字',
          trigger: 'blur',
        },
      ],
    },
    {
      label: '姓名',
      prop: 'name',
      sortable: true,
      search: true,
      fixed: true,
      width: 180,
      rules: [
        {
          required: true,
          message: '姓名不能为空',
          trigger: 'blur',
        },
      ],
    },
    {
      label: '职务',
      prop: 'dutyIdName',
      width: 100,
      component: 'BasicCrudTableSelect',
      crudProps: {
        width: '60%',
        apiSource: { apiGetList: apiDialogGetList },
        option: {
          searchSpan: 8,
          height: '45vh',
        },
      },
      comProps: {
        saveFieldMap: { dutyIdName: 'name', dutyId: 'id' },
      },
    },
    {
      label: '所属部门',
      prop: 'deptId',
      width: 150,
      type: 'tree',
      filterable: true,
      formatter: (row) => row.deptIdName,
      rules: [
        {
          required: true,
          message: '所属部门不能为空',
          trigger: 'blur',
        },
      ],
      dicData: [],
      props: {
        label: 'name',
        value: 'id',
      },
    },
    {
      label: '在职状态',
      prop: 'resignFlag',
      slot: 'status',
      width: 90,
      addDisplay: false,
      editDisplay: false,
      viewDisplay: false,
      hide: true,
      type: 'select',
      search: true,
      dicData: [
        {
          label: '离职',
          value: 'true',
        },
        {
          label: '返聘',
          value: 'false',
        },
      ],
    },
    {
      label: '密码',
      prop: 'password',
      type: 'password',
      width: 180,
      autocomplete: 'off',
      hide: true,
      editDisplay: false,
      rules: [
        {
          required: true,
          message: '密码不能为空',
          trigger: 'blur',
        },
      ],
    },

    {
      label: '确认密码',
      prop: 'confirmPwd',
      type: 'password',
      editDisplay: false,
      width: 180,
      hide: true,
      rules: [
        {
          required: true,
          message: '确认密码不能为空',
          trigger: 'blur',
        },
        {
          validator: (rule, value, callback) => {
            const { formData } = basicCrudRef.value
            if (formData.password !== value) {
              callback(new Error('两次输入密码不一致!'))
            } else {
              callback()
            }
          },
          trigger: ['blur', 'change'],
        },
      ],
    },
    {
      label: '邮箱',
      prop: 'email',
      slot: 'email',
      width: 150,
    },

    {
      label: '移动电话',
      prop: 'mobile',
      sortable: true,
      search: true,
      width: 150,
    },
    {
      label: '固定电话',
      prop: 'fixedPhone',
      sortable: true,
      width: 120,
    },

    {
      label: '联系方式',
      prop: 'contact',
      width: 150,
    },
    {
      label: '性别',
      prop: 'sex',
      width: 80,
      type: 'radio',
      value: 'sex_man',
      dicData: [
        { label: '男', value: 'sex_man' },
        { label: '女', value: 'sex_woman' },
      ],
    },
    {
      label: '描述',
      prop: 'des',
      width: 150,
      type: 'textarea',
      hide: true,
      span: 24,
    },
    {
      label: '状态',
      prop: 'status',
      slot: 'status',
      width: 90,
      display: false,
      fixed: 'right',
    },
  ],
})
// 获取部门数据
const getDepList = async () => {
  depList.value = await apiGetDepTree()
  treeData.value = depList.value
  let idx = option.value.column.findIndex((item) => item.prop === 'deptId')
  if (idx > -1) option.value.column[idx].dicData = depList.value
}
getDepList()

const handleTreeClick = (data) => {
  basicCrudRef.value.pageData.currentPage = 1
  basicCrudRef.value.pageData.pageSize = 10
  basicCrudRef.value.searchData.deptId = data.id
  basicCrudRef.value.getList()
}

// 密码相关操作
const useEditPas = () => {
  const editPasVisible = ref(false)
  const editPasFormRef = ref()
  const editPasFormData = reactive({
    password: undefined,
    confirmPassword: undefined,
    userId: undefined,
  })
  const editPasSubmitLoading = ref(false)
  const editPasRules = {
    password: { required: true, message: '请输入密码', trigger: 'blur' },
    confirmPassword: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (editPasFormData.password !== value) {
            callback(new Error('两次输入密码不一致!'))
          } else {
            callback()
          }
        },
      },
    ],
  }
  const handleOpenEditPas = (row) => {
    editPasVisible.value = true
    editPasFormData.userId = row.id
  }
  const handleBeforeClose = (done) => {
    done()
    editPasFormRef.value && editPasFormRef.value.resetFields()
  }
  watch(
    () => editPasVisible.value,
    (newV) => {
      if (!newV) {
      }
    }
  )
  const handleSubmitEditPas = async () => {
    await apiEditPwd(editPasFormData, editPasSubmitLoading)
    ElMessage.success('修改成功！')
    editPasVisible.value = false
  }
  return {
    editPasVisible,
    editPasFormData,
    editPasRules,
    handleOpenEditPas,
    handleSubmitEditPas,
    editPasSubmitLoading,
    editPasFormRef,
    handleBeforeClose,
  }
}

// 关联角色
const useRelationRole = () => {
  const relationRoleVisible = ref(false)
  const relationRoleOpenBtnLoading = ref(false)
  const relationRoleSubmitLoading = ref(false)
  const apiSource = { apiGetList: apiGetRoleList }
  const relationRoleOption = {
    height: 400,
    menu: false,
    searchSpan: 8,
    reserveSelection: true,
    header: false,
    column: [
      {
        label: '角色编码',
        prop: 'code',
        sortable: true,
        width: 230,
        search: true,
      },
      {
        label: '角色名称',
        prop: 'name',
        width: 200,
        sortable: true,
        search: true,
      },
      {
        label: '描述',
        sortable: true,
        prop: 'des',
        type: 'textarea',
      },
    ],
  }
  const relationRoleDefaultSelectList = ref([])
  const handleOpenRelationRoleDialog = async () => {
    const { selectData } = basicCrudRef.value
    if (selectData.length !== 1) {
      return ElMessage.error('请选择且只能选择一条数据！')
    }
    relationRoleOpenBtnLoading.value = true
    const defaultSelect = await apiGetLinkRoles(selectData[0]['id'])
    relationRoleDefaultSelectList.value = defaultSelect || []
    relationRoleOpenBtnLoading.value = false
    relationRoleVisible.value = true
  }
  const handleRelationRoleSubmit = async (sourceDatas) => {
    await apiRelationRole(
      {
        sourceDatas,
        targetDatas: basicCrudRef.value.selectData,
      },
      relationRoleSubmitLoading
    )
    ElMessage.success('关联角色成功！')
    relationRoleVisible.value = false
    basicCrudRef.value.getList()
  }
  return {
    relationRoleVisible,
    apiSource,
    relationRoleOption,
    handleOpenRelationRoleDialog,
    relationRoleOpenBtnLoading,
    relationRoleSubmitLoading,
    handleRelationRoleSubmit,
    relationRoleDefaultSelectList,
  }
}

const {
  editPasVisible,
  editPasFormData,
  editPasRules,
  handleOpenEditPas,
  handleSubmitEditPas,
  editPasSubmitLoading,
  editPasFormRef,
  handleBeforeClose,
} = useEditPas()

const {
  relationRoleVisible,
  apiSource,
  relationRoleOption,
  handleOpenRelationRoleDialog,
  relationRoleOpenBtnLoading,
  handleRelationRoleSubmit,
  relationRoleSubmitLoading,
  relationRoleDefaultSelectList,
} = useRelationRole()

const handleMoreItemClick = (type, row) => {
  const dataMap = {
    unlock: {
      text: '解锁',
      apiFun: apiUnlock,
    },
    disabled: {
      text: '停用',
      apiFun: apiDisable,
    },
    enable: {
      text: '启用',
      apiFun: apiEnable,
    },
    resign: {
      text: '离职',
      apiFun: apiResign,
    },
    resign: {
      text: '返聘',
      apiFun: apiRehiring,
    },
  }
  const { text, apiFun } = dataMap[type]
  ElMessageBox.confirm(`确认${text}该用户?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        apiFun(row.id)
          .then(() => {
            ElMessage.success(`${text}成功！`)
            done()
            basicCrudRef.value.getList()
          })
          .finally(() => {
            instance.confirmButtonLoading = false
          })
      } else {
        done()
      }
    },
  })
}

const afterUploadSuccess = () => {
  basicCrudRef.value.getList()
}
</script>

<style lang="scss" scoped>
::v-deep {
  .avue-tree {
    .el-cascader-panel {
      display: none;
    }
  }
}
</style>
